<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="第7章 包、模块、函数与变量作用域, 湮灭星空,博客,Python,后端">
    <meta name="description" content="本章对Python代码的组织结构核心：包、模块与函数分别作出讲解。学习完本章后你将对Python代码的组织结构有一个非常清晰的认识。重点是函数，我们除了讲解函数的基本概念外，还将讲解Python灵活的函数参数机制（默认参数、关键字参数与列表">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>第7章 包、模块、函数与变量作用域 | 湮灭星空</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<link rel="alternate" href="/atom.xml" title="湮灭星空" type="application/atom+xml">
</head>

<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper head-container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">湮灭星空</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">湮灭星空</div>
        <div class="logo-desc">
            
            天下寥寥，苍生涂涂，诸子百家，唯我纵横
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友链
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/13.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        第7章 包、模块、函数与变量作用域
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/python/">
                                <span class="chip bg-color">python</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E5%85%A5%E9%97%A8%E4%B8%8E%E8%BF%9B%E9%98%B6/" class="post-category">
                                入门与进阶
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2018-12-14
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2019-12-06
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    2k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    8 分
                </div>
                
				
                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
            
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>本章对Python代码的组织结构核心：包、模块与函数分别作出讲解。学习完本章后你将对Python代码的组织结构有一个非常清晰的认识。重点是函数，我们除了讲解函数的基本概念外，还将讲解Python灵活的函数参数机制（默认参数、关键字参数与列表参数）。</p>
<a id="more"></a>
<h3 id="7-1-while循环与使用场景"><a class="header-anchor" href="#7-1-while循环与使用场景"></a>7-1 while循环与使用场景</h3>
<p>示例：</p>
<pre><code class="language-python">CONDITION = True

while CONDITION:
    print('This is True.')
</code></pre>
<p>为了避免无限循环，</p>
<ul>
<li><code>while</code>后面的判断条件不应该是一个常量，常量总是为 <code>True</code>会导致无限循环，</li>
<li>如果想让 <code>while</code>运行的次数是有限的，在 <code>while</code>内部的代码块里面必须要有能够<strong>影响条件判断的语句</strong>。</li>
</ul>
<p><code>while</code>与 <code>else</code>搭配使用：</p>
<pre><code class="language-python">CONDITION = 1

while CONDITION &lt;= 10:
    CONDITION += 1
    print(CONDITION)
else:
    print('EOF')
</code></pre>
<p>代码解释：</p>
<p>当 <code>CONDITION</code>大于<code>10</code>结束循环之后再执行 <code>else</code>语句。</p>
<h3 id="7-2-for与for-else循环"><a class="header-anchor" href="#7-2-for与for-else循环"></a>7-2 for与for-else循环</h3>
<p><code>for</code>主要是用来遍历/循环 序列或者集合、字典</p>
<pre><code class="language-python">a = [['apple', 'orange', 'banana'], (1,2,3)]
for x in a:
    for y in x:
        print(y, end=' ')	# end=' '表示打印结果使用空格连接
----------------------------------------------------------
apple orange banana 1 2 3 
</code></pre>
<p><code>for</code>循环与<code>else</code>搭配使用：</p>
<pre><code class="language-python">a = [['apple', 'orange', 'banana'], (1,2,3)]
for x in a:
    for y in x:
        print(y)
else:
    print('fruit is gone.')
--------------------------------------------------
运行结果：
apple
ornge
banana
1
2
3
fruit is gone.
</code></pre>
<p>代码解释：</p>
<p>当 <code>for</code>循环结束之后再执行 <code>else</code>语句。</p>
<h4 id="break-和-continue"><a class="header-anchor" href="#break-和-continue"></a>break 和 continue</h4>
<ul>
<li><code>break</code>：强行终止当前循环，并且以后的循环都不会执行</li>
<li><code>continue</code>：跳出循环内的一轮循环，进行下一轮循环</li>
</ul>
<p>循环遍历所有元素：</p>
<pre><code class="language-python">a = [1,2,3]
for x in a:
    print(x)
------------------
运行结果：
1
2
3
</code></pre>
<p>当遍历到<code>2</code>的时候跳出循环：</p>
<pre><code class="language-python">a = [1, 2, 3]
for x in a:
    if x == 2:
        break
    print(x)
---------------------
运行结果：
1
</code></pre>
<p>当遍历到<code>2</code>的时候跳出<code>2</code>这次循环，然后进入下一轮循环：</p>
<pre><code class="language-python">a = [1, 2, 3]
for x in a:
    if x == 2:
        continue
    print(x)
----------------------
运行结果：
1
3
</code></pre>
<h4 id="break-与-else-结合"><a class="header-anchor" href="#break-与-else-结合"></a>break 与 else 结合</h4>
<p>当执行<code>break</code>语句之后，与 <code>for</code>循环结合使用的<code>else</code>语句也不会执行！</p>
<pre><code class="language-python">a = [1, 2, 3]
for x in a:
    if x == 2:
        break
    print(x)
else:
    print('EOF')
-----------------------
运行结果：
1
</code></pre>
<blockquote>
<p>七月心语：</p>
<p>在<code>for</code>与<code>else</code>联合使用的过程中，如果你的 <code>for</code>循环不是正常结束的，而是 <code>break</code>强制结束的，是不会执行 <code>else</code>语句的。这是非常大的误区，一定要注意，很多同学出 bug 就是出在这个地方。</p>
</blockquote>
<h4 id="continue-与-else-结合"><a class="header-anchor" href="#continue-与-else-结合"></a>continue 与 else 结合</h4>
<p><code>continue</code>不影响 <code>else</code>的执行，还是在所有循环结束之后再执行 <code>else</code>语句。</p>
<pre><code class="language-python">a = [1, 2, 3]
for x in a:
    if x == 2:
        continue
    print(x)
else:
    print('EOF')
------------------------
运行结果：
1
3
EOF
</code></pre>
<h4 id="嵌套循环"><a class="header-anchor" href="#嵌套循环"></a>嵌套循环</h4>
<h5 id="内部循环使用-break"><a class="header-anchor" href="#内部循环使用-break"></a>内部循环使用 break</h5>
<pre><code class="language-python">a = [['apple', 'orange', 'banana'], (1,2,3)]
for x in a:
    for y in x:
        if y == 'orange':
            break
        print(y)
else:
    print('fruit is gone.')
---------------------------------------------
运行结果：
apple
1
2
3
fruit is gone.
</code></pre>
<p>代码解释：</p>
<p>上述代码是嵌套循环，<code>break</code>语句终止的是内部的循环，内部循环终止之后会返回到外部循环，外部循环会再次调用内部循环，第一个<code>['apple', 'orange', 'banana']</code>循环结束之后，并不影响<code>(1,2,3)</code>的循环。</p>
<blockquote>
<p>这样的错误是我们在做多维度循环的时候，非常容易出错的地方。</p>
</blockquote>
<p>最终之所以会打印<code>print('fruit is gone.')</code>是因为与 <code>else</code>配对的是外部循环，<code>break</code>终止的是内部循环，外部循环的 <code>else</code>语句不受影响。</p>
<h5 id="外部循环使用-break"><a class="header-anchor" href="#外部循环使用-break"></a>外部循环使用 break</h5>
<pre><code class="language-python">a = [['apple', 'orange', 'banana'], (1,2,3)]
for x in a:
    if 'banana' in x:
        break
    for y in x:
        if y == 'orange':
            break
        print(y)
else:
    print('fruit is gone.')
------------------------------------------------
运行结果：

</code></pre>
<p>代码解释：</p>
<p>上述代码运行结果没有打印任何值，是因为外部循环第一轮循环 <code>list</code>的时候，<code>list</code>内包含 <code>banana</code>遇到了 <code>break</code>直接终止外部循环了，外部循环被终止 <code>else</code>语句也不会执行，所以什么都没有打印。</p>
<h3 id="7-3-for-与-range"><a class="header-anchor" href="#7-3-for-与-range"></a>7-3 for 与 range</h3>
<p>执行10次循环（默认步长为0）：</p>
<pre><code class="language-python">for x in range(0, 10):
    print(x, end=' ')
---------------------------
运行结果：
0 1 2 3 4 5 6 7 8 9 
</code></pre>
<p>打印递增数列（步长为正）：</p>
<pre><code class="language-python">for x in range(0, 10, 2):
    print(x, end=' ')
----------------------------
运行结果：
0 2 4 6 8
</code></pre>
<p>打印递减数列（步长为负）：</p>
<pre><code class="language-python">for x in range(10, 0, -2):
    print(x, end=' ')
---------------------------
运行结果：
10 8 6 4 2 
</code></pre>
<p>思考题：</p>
<p>间隔性的取出 <code>list</code>的元素。</p>
<pre><code class="language-python">a = [1,2,3,4,5,6,7,8]

# 方法1
for x in range(len(a)):
    if x % 2 != 0:
        continue
    print(a[x], end=' ')

print('\n', '-----------')

# 方法2
for x in range(0, len(a), 2):
    print(a[x], end=' ')

print('\n', '-----------')

# 方法3：使用切片
b = a[0:len(a):2]
print(b)
-------------------------------------------------------
运行结果：
1 3 5 7 
 -----------
1 3 5 7 
 -----------
[1, 3, 5, 7]
</code></pre>
<p>使用 <code>for</code>循环确实可以解决问题，但是在解决这个问题上<code>Python</code>有比<code>for</code>更好的解决方式，那就是<strong>切片</strong>。切片在处理这些问题上会更加高效。</p>
<p>所以说有时候我们可以不用 <code>for</code>循环，<code>for</code>循环当然是一种经典的编程方式， 但是对于 <code>Python</code>来讲，<code>Python</code>是一种非常高级的语言，它可以为我们提供更多的避免写 <code>for</code>的方式。</p>
<h3 id="7-4-新篇章导言"><a class="header-anchor" href="#7-4-新篇章导言"></a>7-4 新篇章导言</h3>
<p>会写代码非常容易 业务</p>
<p>高性能、封装性（可复用）、抽象</p>
<p>直白</p>
<p>美与不美</p>
<h3 id="7-5-python工程的组织结构：包-模块儿-类"><a class="header-anchor" href="#7-5-python工程的组织结构：包-模块儿-类"></a>7-5 Python工程的组织结构：包、模块儿、类</h3>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-05-14-144428.jpg" alt="image-20181025181605484"></p>
<h3 id="7-6-python包与模块的名字"><a class="header-anchor" href="#7-6-python包与模块的名字"></a>7-6 Python包与模块的名字</h3>
<p>文件夹和<code>Python</code>包是有区别的，区别在于<strong>包</strong>必须包含<code>__init__.py</code>文件。</p>
<p><code>__init__.py</code>文件也是一个模块，该文件可以为空，只用作来标识一个包，也可以在文件内部写代码。</p>
<p>获取包下面的文件可以使用<code>包名.文件名</code>的形式，例如 ：<code>test</code>包下的 <code>test1</code>文件，可以写作<code>test.test1</code></p>
<p>那么如何获取<code>__init__.py</code>文件呢？</p>
<p><code>__init__.py</code>的文件名比较特殊，就叫做<code>包名</code>。例如：<code>app</code>包下的<code>__init__.py</code>文件调用的时候就写作<code>app</code></p>
<h3 id="7-7-import导入模块"><a class="header-anchor" href="#7-7-import导入模块"></a>7-7 import导入模块</h3>
<pre><code class="language-python">import module
import module as something
</code></pre>
<h3 id="7-8-from-import-导入变量"><a class="header-anchor" href="#7-8-from-import-导入变量"></a>7-8 from import 导入变量</h3>
<p><code>from import</code>可以导入<strong>函数</strong>、<strong>变量</strong>、<strong>模块</strong></p>
<pre><code class="language-python">from module import something
</code></pre>
<p>导入<code>module</code>内的所有内容</p>
<pre><code class="language-python">from module import *
</code></pre>
<p>可以不可以控制<code>from module import *</code>的行为只导入我们想导入的内容呢？</p>
<p>答案是可以的。需要在 <code>module</code>文件中添加<code>__all__</code>变量。</p>
<pre><code class="language-python"># module.py
__all__ = ['a', 'b', 'c']	# 这样写之后，在使用 import * 导入的时候只会导入列表内的内容

a = 1
b = 2
c = 3
d = 4
e = 5
</code></pre>
<blockquote>
<p>内置变量（内置属性）：</p>
<p>像<code>__all__</code>这种双下划线开头的变量，被称为模块的内置变量或者内置属性。</p>
<p>上述示例是<code>__all__</code>作用于 <code>module</code>， 同样作用于<strong>包</strong>。</p>
</blockquote>
<h3 id="7-9-init-py-的用法"><a class="header-anchor" href="#7-9-init-py-的用法"></a>7-9 _<em>init</em>_.py 的用法</h3>
<p><code>Python</code>代码过长需要换行的时候，在当前行末尾加上<code>\</code>换行。</p>
<pre><code class="language-python">form module import a, b,\
c
</code></pre>
<p>也可以在被导入对象外加<code>()</code>换行。</p>
<pre><code class="language-python">form module import (a, b,
c)
</code></pre>
<p><code>()</code>括号可以换行。</p>
<h4 id="导入时自动执行"><a class="header-anchor" href="#导入时自动执行"></a>导入时自动执行</h4>
<p>当一个包被导入的时候，<code>__init__.py</code>文件将首先被 <code>Python</code> 自动执行。</p>
<h4 id="批量导入"><a class="header-anchor" href="#批量导入"></a>批量导入</h4>
<p><code>__init__.py</code>文件可以用作<strong>批量导入</strong>。</p>
<h3 id="7-10-包与模块的几个常见错误"><a class="header-anchor" href="#7-10-包与模块的几个常见错误"></a>7-10 包与模块的几个常见错误</h3>
<ul>
<li>包和模块是不会被重复导入的</li>
<li>避免循环导入</li>
</ul>
<p><code>Python</code>在导入模块的时候就会执行模块里面的所有代码，无论在程序里导入多少次某一个模块，该模块在导入阶段只会执行一次。</p>
<h3 id="7-11-模块内置变量"><a class="header-anchor" href="#7-11-模块内置变量"></a>7-11 模块内置变量</h3>
<h3 id="7-12-入口文件和普通模块内置变量的区别"><a class="header-anchor" href="#7-12-入口文件和普通模块内置变量的区别"></a>7-12 入口文件和普通模块内置变量的区别</h3>
<h3 id="7-13-name-的经典应用"><a class="header-anchor" href="#7-13-name-的经典应用"></a>7-13 __name__的经典应用</h3>
<h3 id="7-14-相对导入和绝对导入-一"><a class="header-anchor" href="#7-14-相对导入和绝对导入-一"></a>7-14 相对导入和绝对导入 一</h3>
<h3 id="7-15-相对导入和绝对导入-二"><a class="header-anchor" href="#7-15-相对导入和绝对导入-二"></a>7-15 相对导入和绝对导入 二</h3>

<div id="gitalk-container"></div>
<script src="https://cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script><link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css"><script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

		<script>
		var gitalkConfig = {"clientID":"9eb5bc3ac1e1ff3ddac0","clientSecret":"4b7ae28042282281295075c2bf0c97ff1791cfeb","repo":"HexoBlogComments","owner":"Annihilater","admin":["Annihilater"],"distractionFreeMode":false};
	    gitalkConfig.id = md5(location.pathname);
		var gitalk = new Gitalk(gitalkConfig);
	    gitalk.render("gitalk-container");
	    </script>
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn" rel="external nofollow noreferrer">湮灭星空</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn/2018/12/14/python3-ru-men-yu-jin-jie-shi-pin-bi-ji/di-7-zhang-bao-mo-kuai-han-shu-yu-bian-liang-zuo-yong-yu/">https://www.klause.cn/2018/12/14/python3-ru-men-yu-jin-jie-shi-pin-bi-ji/di-7-zhang-bao-mo-kuai-han-shu-yu-bian-liang-zuo-yong-yu/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/python/">
                                    <span class="chip bg-color">python</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/01/25/python3-ru-men-yu-jin-jie-shi-pin-bi-ji/di-14-zhang-pythonic-yu-python-za-ji/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/3.jpg" class="responsive-img" alt="第14章 Pythonic与Python杂记">
                        
                        <span class="card-title">第14章 Pythonic与Python杂记</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本章我们将大量扩展Python的优秀写法，学会如何写出优质的Pythonic风格的代码。包括：如何让字典保持有序、lmbda表达式的应用等高级Python知识

14-1 导言

七月心语：
其实有时候写代码，看着自己写的一段一段的代码把它
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2019-01-25
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%85%A5%E9%97%A8%E4%B8%8E%E8%BF%9B%E9%98%B6/" class="post-category">
                                    入门与进阶
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/python/">
                        <span class="chip bg-color">python</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2018/12/03/tools/14-ge-sou-suo-google-deng-sou-suo-yin-qing-gao-ji-sou-suo-zhi-ling-wang-zhan-you-hua-ren-yuan-bi-bei-ji-neng/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/8.jpg" class="responsive-img" alt="14个 Google 高级搜索指令">
                        
                        <span class="card-title">14个 Google 高级搜索指令</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            14个 Google 高级搜索指令
双引号 “&quot;
双引号 ：把关键词放到双引号内，搜索引擎默认采用模糊匹配方式，会将词组进行拆分以及同义词分析，此时加上双引号可以强制进行完全匹配搜索。即：双引号内的内容必须完整并连续的出现。注意双
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2018-12-03
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Tools/" class="post-category">
                                    Tools
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/google/">
                        <span class="chip bg-color">google</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>

    
<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">年份</span>
            <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">199.2k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    window.setTimeout("siteTime()", 1000);
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2019";
                    var startMonth = "6";
                    var startDate = "28";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="http://www.beian.miit.gov.cn" target="_blank">皖ICP备18005729号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Annihilater" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:yanmiexingkong@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>





    <a href="https://twitter.com/" class="tooltipped" target="_blank" data-tooltip="关注我的Twitter: https://twitter.com/" data-position="top" data-delay="50">
        <i class="fab fa-twitter"></i>
    </a>







    <a href="https://www.zhihu.com/" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>

    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
